<template>
  <div class="dashboard-container">
    <div class="app-container">
      <PageTools>
        <template #after>
          <el-button type="primary" size="small" icon="el-icon-plus" @click="additem(1,'0')">新增权限</el-button>
        </template>
      </PageTools>

      <!-- 表格 -->
      <!-- 
        row-key
        1. 要求数组数据要有children的属性
        2. 绑定的值要是唯一的
      -->
      <el-table border :data="list" row-key="id">
        <el-table-column label="名称" prop="name" />
        <el-table-column label="标识" prop="code" align="center" />
        <el-table-column label="描述" prop="description" align="center" />
        <el-table-column label="操作" align="center">
          <template v-slot="{row}">
            <!-- type=1 是一级树形 type=2 是二级树形 -->
            <el-button v-show="row.type === 1" type="text" @click="additem(2,row.id)">添加</el-button>
            <el-button type="text" @click="upditem(row.id)">编辑</el-button>
            <el-button type="text" @click="delitem(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 新增权限 -->
      <addPermission 
        ref="addPermission" 
        :showPermission.sync="showPermission"/>
    </div>
  </div>
</template>

<script>
import { getPermissionList,delPermission } from "@/api/permission";
import { tranListToTreeData } from "@/utils";
import addPermission from './component/add-permission'
export default {
  name: 'permission',
  data () {
    return {
      list: [], // 所有权限的数据
      showPermission: false, // 新增权限的弹框状态
    }
  },
  created () {
    this.getPermissionList()
  },
  methods: {
    async getPermissionList() {
      // 这里为什么要 '0' 而不是 '' 因为根id是 '0'
      this.list = tranListToTreeData(await getPermissionList(),'0')
    },
    async upditem(id) {
      await this.$refs.addPermission.getPermissionDetail(id)
      this.showPermission = true
    },
    additem(type, id) {
      /**
       *    type: '', // 0 是一级 1是二级
       *    pid: ''
       */
      this.$refs.addPermission.formData.type = type,this.$refs.addPermission.formData.pid = id
      this.showPermission = true
    },
    async delitem(id) {
      await this.$confirm('确定要删除该数据吗')
      await delPermission(id)
      this.getPermissionList()
      this.$message.success('删除成功')
    }
  },
  components: {
    addPermission
  }
}
</script>

<style>

</style>
